<template>
  <div class="con">
    <el-form
      :model="formData"
      label-width="70px"
      :inline="true"
      ref="formEle"
      class="flex formTop"
    >
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="formData.menuName"
          placeholder="请输入菜单名称查找"
        />
      </el-form-item>
      <el-form-item label="菜单状态" prop="menuState">
        <el-select v-model="formData.menuState" placeholder="请选择">
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formEle)">查询</el-button>
        <el-button @click="resetForm(formEle)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <div class="table-list">
      <div class="btnTop">
        <el-button type="primary" @click="handleAdd">添加菜单</el-button>
      </div>
      <el-table
        :data="MenuList"
        style="width: 100%; margin-bottom: 20px"
        row-key="_id"
      >
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.property"
          :label="item.label"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" class="last-btn">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogFormType == 'Edit' ? '编辑' : '创建角色'"
    @closed="clearDialog(dialogForm)"
    width="45%"
  >
    <el-form
      :model="dialogFormData"
      label-width="100px"
      ref="dialogForm"
      status-icon
      :rules="rules"
    >
      <el-form-item label="父级菜单" prop="parentId">
        <el-cascader
          v-model="dialogFormData.parentId"
          :options="MenuList"
          :props="{ checkStrictly: true, value: '_id', label: 'menuName' }"
          clearable
        />
        <span> 不选，则直接创建一级菜单</span>
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="dialogFormData.menuType" class="ml-4">
          <el-radio :label="1" size="large">菜单</el-radio>
          <el-radio :label="2" size="large">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="dialogFormData.menuName"></el-input>
      </el-form-item>
      <template v-if="dialogFormData.menuType == 1">
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="dialogFormData.icon"></el-input>
        </el-form-item>
        <el-form-item label="路由地址" prop="path">
          <el-input v-model="dialogFormData.path"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="dialogFormData.component"></el-input>
        </el-form-item>
      </template>
      <el-form-item label="权限标识" prop="menuCode" v-else>
        <el-input v-model="dialogFormData.menuCode"></el-input>
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuState">
        <el-radio-group v-model="dialogFormData.menuState" class="ml-4">
          <el-radio :label="1" size="large">正常</el-radio>
          <el-radio :label="2" size="large">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearDialog">取消</el-button>
        <el-button type="primary" @click="dialogConfirm(dialogForm)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reqResult, menuinfo, formInfo } from "../types/type";
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  formateDate,
  showMassage,
  classifyMenu,
  ShowElMessageBox,
} from "../untils/common";
import request from "../api/requestApi";
const formData = reactive({
  menuName: "",
  menuState: 1,
});

const rules = reactive<FormRules>({
  menuName: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 1 to 5", trigger: "blur" },
  ],
});
// 菜单信息
const MenuList = ref<menuinfo[]>([]);
onMounted(() => {
  reqMenuList();
});

// 请求菜单
const reqMenuList = async () => {
  let res = (await request.getMenuList({ ...formData })) as reqResult<
    menuinfo[]
  >;
  let newarr: menuinfo[] = [];
  // 筛选菜单
  if (formData.menuName !== "") {
    MenuList.value = res.data;
    return false;
  }
  classifyMenu(newarr, res.data);
  MenuList.value = newarr;
};

// 查询与重置
let formEle = ref<FormInstance>();
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      reqMenuList();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 新增与编辑与删除
const handleAdd = () => {
  openDialog("Add");
};
const handleEdit = (index: number, row: formInfo) => {
  Object.assign(dialogFormData, row);
  openDialog("Edit");
};

const handleDelete = async (index: number, row: formInfo) => {
  dialogFormType.value = "Del";
  async function fn() {
    let res = (await request.OperateMenu({
      _id: row._id,
      dialogFormType: dialogFormType.value,
      ...dialogFormData,
    })) as reqResult<null>;
  }
  ShowElMessageBox("确认删除吗？", "删除成功", fn, reqMenuList);
};

// table字段
const columns = ref([
  {
    property: "menuName",
    label: "菜单名称",
  },
  {
    property: "icon",
    label: "图标",
  },
  {
    property: "menuType",
    label: "菜单类型",
    formatter(row: string, column: string, cellValue: string) {
      return {
        1: "菜单",
        2: "按钮",
      }[cellValue];
    },
  },
  {
    property: "menuCode",
    label: "权限标识",
  },
  {
    property: "path",
    label: "路由地址",
  },
  {
    property: "component",
    label: "组件路径",
  },
  {
    property: "menuState",
    label: "菜单状态",
    formatter(row: string, column: string, cellValue: string) {
      return {
        1: "正常",
        2: "停用",
      }[cellValue];
    },
  },
  {
    property: "createTime",
    label: "注册时间",
    width: "220px",
    formatter(row: string, column: string, cellValue: string) {
      return formateDate(new Date(cellValue));
    },
  },
]);

// dialog对话框
const dialogFormData = reactive<formInfo>({
  parentId: [null],
  menuName: "",
  menuCode: "",
  menuType: 1,
  icon: "",
  path: "",
  component: "",
  menuState: 1,
});
let initialize: formInfo = {
  parentId: [null],
  menuName: "",
  menuCode: "",
  menuType: 1,
  icon: "",
  path: "",
  component: "",
  menuState: 1,
};
const dialogFormType = ref<string>("");
let dialogFormVisible = ref<boolean>(false);
let dialogForm = ref<FormInstance>();

function openDialog(type: string) {
  dialogFormType.value = type;
  dialogFormVisible.value = true;
}

function clearDialog(formEl: FormInstance) {
  dialogFormVisible.value = false;
  console.log(formEl);
  formEl.resetFields();
  goinitialize()
}
function dialogConfirm(formEl: FormInstance) {
  if (!formEl) return;
  if (dialogFormData.parentId === null) {
    dialogFormData.parentId = [null];
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = (await request.OperateMenu({
        dialogFormType: dialogFormType.value,
        ...dialogFormData,
      })) as reqResult<null>;
      if (res.code == 200) {
        showMassage(res.msg, "success");
        reqMenuList();
      } else {
        showMassage(res.msg, "error");
      }
      dialogFormVisible.value = false;
    }
  });
  formEl.resetFields();
  goinitialize()
}
// 初始化操作
const goinitialize = () => {
  dialogFormData.menuName = "";
  dialogFormData.icon = "";
  dialogFormData.path = "";
};
</script>

<style lang="postcss" scoped>
.con {
  @apply flex-1 flex flex-col;
  width: 100%;
}
.formTop {
  height: 60px;
  @apply bg-light-50;
  padding: 20px;
  line-height: 60px;
  border-radius: 5px;
  /* justify-content: space-between; */
  .el-form-item {
    margin-bottom: 0;
    margin-right: 150px;
    align-self: center;
  }
}
.table-list {
  @apply bg-light-50 flex-1 flex flex-col;
  border-radius: 5px;
  overflow: hidden;
  margin: 20px 0 0 0;
  .btnTop {
    padding: 20px;
  }
}
.el-form-item :deep(.el-form-item__label) {
  line-height: 40px;
  height: 40px;
}
</style>
